package org.smart4j.framework.helper;

import com.sun.xml.internal.bind.v2.TODO;

import javax.sql.DataSource;
import java.sql.*;
import java.util.HashSet;
import java.util.Set;


/**
 * @author djw
 * @time 2017/10/27 15:30
 */
public final class DatabaseHelper {
    private static  ThreadLocal<Connection> CONNECTION_HOLDER=new ThreadLocal<>();
    private static final String driver="com.mysql.jdbc.Driver";
    private static final String url="jdbc:mysql://localhost:3306/demo";
    private static final String username="root";
    private static final String password="root";
    public static void beginTransaction(){
        Connection conn=getConnection();
        if(conn!=null){
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                CONNECTION_HOLDER.set(conn);
            }
        }
    }

    public static void commitTransaction(){
        Connection conn=getConnection();
        if(conn!=null){
            try {
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }

    public static void rollbackTransaction(){
        Connection conn=getConnection();
        if(conn!=null){
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }

    private static Connection getConnection() {
        Connection conn=CONNECTION_HOLDER.get();
        if(conn==null){
            try {
                Class.forName(driver);
                conn=DriverManager.getConnection(url,username,password);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                CONNECTION_HOLDER.set(conn);
            }
        }
        return conn;
    }
    
    public static String query(String sql, String username) {
        Connection conn=getConnection();
        return "";
    }

    public static Set<String> querySet(String sql, String username) {
        return new HashSet<>();
    }

    public static DataSource getDataSource() {
    }
}
